<template>
    <div class="address-list-view">
        <div class="page-header">
            <h1>收货地址</h1>
            <p>管理您的收货地址</p>
        </div>

        <div class="actions">
            <el-button type="primary" @click="openAddressDialog()">新增地址</el-button>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
            <LoadingSpinner />
        </div>

        <!-- 空状态 -->
        <div v-else-if="!addresses.length" class="empty-container">
            <EmptyState title="暂无地址" description="您还没有添加任何收货地址" :icon="Location" />
        </div>

        <!-- 地址列表 -->
        <div v-else class="address-list-container">
            <el-card v-for="address in addresses" :key="address.id" class="address-card">
                <div class="address-card-body">
                    <div class="address-info">
                        <p><strong>{{ address.receiverName }}</strong> {{ address.phone }}</p>
                        <p>{{ address.province }} {{ address.city }} {{ address.district }}</p>
                        <p>{{ address.detailAddress }}</p>
                    </div>
                    <div class="address-actions">
                        <el-tag v-if="address.isDefault" type="success">默认地址</el-tag>
                        <el-button type="text" @click="openAddressDialog(address)">编辑</el-button>
                        <el-button type="text" @click="deleteAddress(address.id)">删除</el-button>
                        <el-button v-if="!address.isDefault" type="text" @click="setDefaultAddress(address.id)">设为默认</el-button>
                    </div>
                </div>
            </el-card>
        </div>

        <!-- 地址编辑/新增弹窗 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
            <el-form :model="addressForm" :rules="addressRules" ref="addressFormRef" label-width="80px">
                <el-form-item label="收货人" prop="receiverName">
                    <el-input v-model="addressForm.receiverName" />
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="addressForm.phone" />
                </el-form-item>
                <el-form-item label="省市区" prop="city">
                    <el-input v-model="addressForm.province" placeholder="省" style="width: 30%;" />
                    <el-input v-model="addressForm.city" placeholder="市" style="width: 30%;" />
                    <el-input v-model="addressForm.district" placeholder="区" style="width: 30%;" />
                </el-form-item>
                <el-form-item label="详细地址" prop="detailAddress">
                    <el-input type="textarea" v-model="addressForm.detailAddress" />
                </el-form-item>
                <el-form-item label="默认地址">
                    <el-switch v-model="addressForm.isDefault" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveAddress">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { getAddressList, addAddress, updateAddress, deleteAddress as deleteAddressApi, setDefaultAddress as setDefaultAddressApi } from '@/api/modules/address'
import type { Address } from '@/types'
import LoadingSpinner from '@/components/base/LoadingSpinner.vue'
import EmptyState from '@/components/base/EmptyState.vue'
import { Location } from '@element-plus/icons-vue'

const addresses = ref<Address[]>([])
const loading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)

const addressFormRef = ref<FormInstance>()
const addressForm = reactive<Partial<Address>>({
    id: undefined,
    receiverName: '',
    phone: '',
    province: '',
    city: '',
    district: '',
    detailAddress: '',
    isDefault: 0,
})

const addressRules: FormRules = {
    receiverName: [{ required: true, message: '请输入收货人', trigger: 'blur' }],
    phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
    city: [{ required: true, message: '请输入省市区', trigger: 'blur' }],
    detailAddress: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
}

const dialogTitle = computed(() => (isEdit.value ? '编辑地址' : '新增地址'))

const loadAddresses = async () => {
    try {
        loading.value = true
        addresses.value = await getAddressList()
    } catch (error) {
        console.error('获取地址列表失败:', error)
    } finally {
        loading.value = false
    }
}

const openAddressDialog = (address?: Address) => {
    if (address) {
        isEdit.value = true
        Object.assign(addressForm, address)
    } else {
        isEdit.value = false
        Object.assign(addressForm, {
            id: undefined,
            receiverName: '',
            phone: '',
            province: '',
            city: '',
            district: '',
            detailAddress: '',
            isDefault: false,
        })
    }
    dialogVisible.value = true
}

const saveAddress = async () => {
    if (!addressFormRef.value) return
    await addressFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                if (isEdit.value) {
                    await updateAddress(addressForm as Address)
                    ElMessage.success('地址更新成功')
                } else {
                    await addAddress(addressForm as Address)
                    ElMessage.success('地址添加成功')
                }
                dialogVisible.value = false
                loadAddresses()
            } catch (error) {
                console.error('保存地址失败:', error)
                ElMessage.error('保存失败', '请重试')
            }
        }
    })
}

const deleteAddress = async (id: number) => {
    try {
        await ElMessageBox.confirm('确定要删除该地址吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        })
        await deleteAddressApi(id)
        ElMessage.success('地址删除成功')
        loadAddresses()
    } catch (error) {
        console.error('删除地址失败:', error)
    }
}

const setDefaultAddress = async (id: number) => {
    try {
        await setDefaultAddressApi(id)
        ElMessage.success('默认地址设置成功')
        loadAddresses()
    } catch (error) {
        console.error('设置默认地址失败:', error)
        ElMessage.error('设置失败，请重试')
    }
}

onMounted(() => {
    loadAddresses()
})
</script>

<style scoped>
.address-list-view {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
}

.page-header {
    text-align: center;
    margin-bottom: 30px;
}

.page-header h1 {
    color: #333;
    margin-bottom: 10px;
    font-size: 28px;
    font-weight: 600;
}

.page-header p {
    color: #666;
    font-size: 16px;
}

.actions {
    margin-bottom: 20px;
    text-align: right;
}

.loading-container,
.empty-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 300px;
}

.address-list-container {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.address-card {
    border-radius: 8px;
}

.address-card-body {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
}

.address-info p {
    margin: 5px 0;
    color: #666;
}

.address-actions {
    display: flex;
    align-items: center;
    gap: 10px;
}
</style>
